// ----------------------------------------------------------------------------
// Copyright 2006, Martin D. Flynn
// All rights reserved
// ----------------------------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
// http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
// Description:
//  This class is intended to be run from the command line and accepts a JAD
//  file as the single argument.  The size of the corresponding JAR file is
//  inserted into the "MIDlet-Jar-Size:" field in the JAD file (replacing any
//  value that may already be present in this field).  The JAD file is then
//  re-written in-place (so best to only modify a copy of the JAD file).
// ----------------------------------------------------------------------------
// Change History:
//  2006/03/29  Martin D. Flynn
//      Initial release
// ----------------------------------------------------------------------------
package org.opendmtp.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Used to update JAD file with the size of the jar file. The size of the corresponding JAR file is
 * inserted into the "MIDlet-Jar-Size:" field in the JAD file (replacing any value that may already
 * be present in this field).
 * 
 * @author Martin D. Flynn
 * @author Guanghong Yang
 * 
 */
public class UpdateJAD {

  // ------------------------------------------------------------------------

  private static final String MIDLET_JAR_SIZE = "MIDlet-Jar-Size:";

  // ------------------------------------------------------------------------

  /**
   * Outputs message to the system default output.
   * 
   * @param msg The message.
   */
  private static void println(String msg) {
    String m = msg.endsWith("\n") ? msg : (msg + "\n");
    System.out.println(m);
  }

  /**
   * Main method of the class. Update the JAD file with the JAR file size.
   * 
   * @param args Contains the name of the JAD file.
   */
  public static void main(String args[]) {

    /* get jad file */
    if (args.length < 1) {
      println("UpdateJAD: Missing JAD file");
      System.exit(1);
    }
    else if (!args[0].endsWith(".jad")) {
      println("UpdateJAD: Invalid JAD file specified");
      System.exit(1);
    }
    String jadFileName = args[0];
    File jadFile = new File(jadFileName);
    if (!jadFile.isFile()) {
      println("UpdateJAD: JAD file does not exist '" + jadFileName + "'");
      System.exit(1);
    }

    /* get jar file */
    String jarFileName = jadFileName.substring(0, jadFileName.length() - 4) + ".jar";
    File jarFile = new File(jarFileName);
    if (!jarFile.isFile()) {
      println("UpdateJAD: JAR file does not exist '" + jarFileName + "'");
      System.exit(1);
    }
    long jarFileSize = jarFile.length();

    /* read jad file */
    byte jadBytes[] = new byte[(int) jadFile.length()];
    FileInputStream fis = null;
    try {
      fis = new FileInputStream(jadFile);
      fis.read(jadBytes);
    }
    catch (IOException ioe) {
      println("UpdateJAD: Error reading JAD file [" + ioe + "]");
      System.exit(1);
    }
    finally {
      try {
        fis.close();
      }
      catch (Throwable t) {
      }
    }
    String jadString = new String(jadBytes);
    StringBuffer jadBuffer = new StringBuffer(jadString);
    int jadLen = jadString.length();

    /* find "MIDlet-Jar-Size:" */
    int p = jadBuffer.indexOf(MIDLET_JAR_SIZE);
    if (p < 0) {
      println("UpdateJAD: '" + MIDLET_JAR_SIZE + "' not found in JAD file");
      System.exit(1);
    }
    p += MIDLET_JAR_SIZE.length();
    while ((p < jadLen) && (jadBuffer.charAt(p) == ' ')) {
      p++;
    }

    /* find end of line */
    // skip over existing size entries
    int n = p;
    while ((n < jadLen) && (jadBuffer.charAt(n) != '\n') && (jadBuffer.charAt(n) != '\r')) {
      n++;
    }

    /* new buffer */
    // replace old size value with new size value
    jadBuffer.replace(p, n, String.valueOf(jarFileSize));

    /* re-write jad file */
    // JAD file is re-written in-place.
    byte newJBytes[] = jadBuffer.toString().getBytes();
    FileOutputStream fos = null;
    try {
      fos = new FileOutputStream(jadFile);
      fos.write(newJBytes);
    }
    catch (IOException ioe) {
      println("UpdateJAD: Error writing new JAD file [" + ioe + "]");
      System.exit(1);
    }
    finally {
      try {
        fos.close();
      }
      catch (Throwable t) {
      }
    }

    /* done */
    println("UpdateJAD: JAD file overwritten with new JAR size [" + jarFileSize + "]");
    // System.exit(0);

  }

}
